package data.net;

import java.io.IOException;
import java.util.HashSet;
import java.util.Set;

import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
import org.jsoup.select.NodeTraversor;

import ui.swing.VersionUtil;

public class CmbReaschHunter extends Thread {
	private Set<String> researhers = new HashSet<String>();
	private Set<String> newResearhers = new HashSet<String>();
	
	public CmbReaschHunter(){
	}
	
	public void handle(){
		String url = "http://www.newone.com.cn/research/list?id=2";
		
		Document doc = null;
		try {
			doc = Jsoup.connect(url).get();
		} catch (IOException e) {
			e.printStackTrace();
		}
		
		if(doc==null){
			return;
		}
		Element el = doc.getElementById("td5");
		Elements links = el.getElementsByTag("a");
		for (Element link : links) {  
			String linkHref = link.attr("href");  
			Document doc2 = null;
			try {
				doc2 = Jsoup.connect("http://www.newone.com.cn"+linkHref).get();
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			if(doc2==null){
				return;
			}
			Elements tables = doc2.getElementsByClass("c_table1");
			boolean isPrint = false;
			for(Element table : tables){
				Elements tds = table.getElementsByTag("td");
				for(Element td : tds){
					String plainText = getPlainText(td);
					if(isPrint&&plainText.indexOf("强烈推荐-A")>0){
						String[] titles = plainText.split("\n");
						String title = titles[0].substring(5);
						if(!researhers.contains(title)){
							newResearhers.add(title);
							researhers.add(title);
						}
					}
					isPrint = plainText.equals("摘要：");
				}
			}
		}
	}
	
	@Override
	public void run() {
		while(true){
			handle();
			if(!newResearhers.isEmpty()){
				StringBuffer sb = new StringBuffer();
				for (String str : newResearhers) {
					sb.append(str);
					sb.append("\n");
				}
				new VersionUtil(sb.toString());
				newResearhers.clear();
			}
			try {
				Thread.sleep(60000);
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
		}
	}
	
	public String getPlainText(Element element) {
        FormattingVisitor formatter = new FormattingVisitor();
        NodeTraversor traversor = new NodeTraversor(formatter);
        traversor.traverse(element); // walk the DOM, and call .head() and .tail() for each node

        return formatter.toString();
    }
	
	public static void main(String[] args) {
		CmbReaschHunter crh = new CmbReaschHunter();
		crh.start();
	}

}
